<template>
    <div>
      <el-table border style="margin-bottom: 20px;" :data="menuPermissionList" :expand-row-keys="expandKeys" row-key="admin_menu_id">
        <el-table-column prop="menu_name" label="名称" />
        <el-table-column prop="menu_url" label="权限值" />
  
        <!-- <el-table-column prop="toCode" label="跳转权限值" /> -->
  
        <el-table-column label="操作">
          <template v-slot="{row}">
            <el-button :type="row.is_disable ==0?'warning':'danger'" size="small" :icon="Warning" :title="row.is_disable ==0?'点击禁用':'解除禁用'" @click="disable(row)" />

            <el-button v-btn-roles="'/admin.Menu/add'" :disabled="row.is_disable===1" type="primary" :icon="Plus" size="small" @click="toAddPermission(row)" title="添加菜单" />
  
            <el-button v-btn-roles="'/admin.Menu/edit'" :disabled="row.is_disable===1" type="primary" :icon="Edit" size="small" @click="toUpdatePermission(row)" title="修改菜单" />
  
            <el-button v-btn-roles="'/admin.Menu/dele'" type="danger" :icon="Delete" size="small" @click="removePermission(row)" title="删除" />
          </template>
        </el-table-column>
      </el-table>
      <el-dialog v-model="dialogVisible" :title="dialogTitle" @close="resetData">
        <el-form ref="permissionRef" :model="permission" :rules="permissionRules" label-width="120px">

          <el-form-item label="id" prop="menu_pid"  >
            <el-input v-model="permission.menu_pid" :disabled="isorno" placeholder="选择 0 同级添加" />
          </el-form-item>

          <el-form-item label="名称" prop="menu_name">
            <el-input v-model="permission.menu_name" />
          </el-form-item>
  
          <el-form-item label="权限值" prop="menu_url">
            <el-input v-model="permission.menu_url" />
          </el-form-item>
        </el-form>
  
        <template #footer>
          <el-button @click="resetData">取 消</el-button>
          <el-button type="primary" @click="addOrUpdatePermission">确 定</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script lang="ts">
  export default {
    name: 'Permission'
  }
  </script>
  
  <script lang="ts" setup>
    import { ElTable, ElTableColumn, ElButton, ElDialog, ElForm, ElFormItem, ElInput, type FormInstance, ElMessage, ElMessageBox } from "element-plus";
    import {Plus, Edit, Delete,Warning} from '@element-plus/icons-vue'
    import { reactive, ref, computed, onMounted, nextTick } from "vue";
    import { getPermissionListApi, removePermissionApi, reqGetDisabled, saveOrUpdatePermissionApi } from "@/api/acl/permission";
    import { relative } from "path-browserify";
    const permissionRef = ref<FormInstance>()
    const menuPermissionList = ref<any>([])
    const expandKeys = ref<any>([])
    const dialogVisible = ref<boolean>(false)
    const isorno = ref<any>(false)
    const permission = reactive<any>({ // 要操作的菜单权限对象
          type: 0,
          menu_name: '',
          menu_url: '',
          menu_pid:'',
          menu_sort:'',
    })
    onMounted(() => {
      fetchPermissionList()
    })
  
    /* 
    动态计算得到Dialog的标题
    */
    const dialogTitle = computed(() => {
      const { type } = permission
      if (type == 1) {
        return '修改菜单'
      } else {
        return '添加菜单'
      }
    })
  
    /* 
    根据权限的等级来计算确定校验规则
    */
    const permissionRules = computed(() => {
      // 菜单权限校验的规则
      const menuRules = { 
        menu_name: [{required: true, message: '名称必须输入'}],
        menu_url: [{required: true, message: '权限值必须输入'}],
      }
      // 按钮功能权限校验的规则
      const btnRules = { 
        menu_name: [{required: true, message: '名称必须输入'}],
        menu_url: [{required: true, trigger: 'blur', message: '功能权限值必须输入'}]
      }
      return btnRules
    })
  
    /* 
    请求获取权限菜单数据列表
    */
    const fetchPermissionList = async () => {
      const result = await getPermissionListApi()
      console.log(result);
      
      menuPermissionList.value = result.list
      expandKeys.value = [menuPermissionList.value[0].admin_menu_id]
    }
  
    /* 
    显示添加权限的界面(菜单或功能)
    */
    const toAddPermission = (row: any) => {
      dialogVisible.value = true
      isorno.value = row.menu_pid ==0?false:true
      permission.menu_pid = row.admin_menu_id    // pid ==> parentId 父权限数据的id
      
      // 清除校验(必须在界面更新之后)
      // 注意: 校验规则是动态的, nextTick清除后还会显示错误信息, 应该是在nextTick后进行了校验
      /* nextTick(() => {
        permissionRef.value?.clearValidate()
      }) */
      setTimeout(() => {
        permissionRef.value?.clearValidate()
      }, 0);
    }
  
    /* 
    显示菜单添加或更新的dialog
    */
    const toUpdatePermission = (row: any) => {
      permission.type = 1
      dialogVisible.value = true
      isorno.value = true
      Object.assign(permission, row)
  
      // 清除校验(必须在界面更新之后)
      // nextTick(() => permissionRef.value?.clearValidate())
      setTimeout(() => {
        permissionRef.value?.clearValidate()
      }, 0);
    }
  
    /* 
    删除某个权限节点
    */    
    const removePermission = (permission: any) => {
      const id = String(permission.admin_menu_id)
      
      ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        type: 'warning'
      }).then(async () => {
        await removePermissionApi(id)
        ElMessage.success('删除成功!')
        fetchPermissionList()
      }).catch((error) => {
        if (error==='cancel') {
          ElMessage({
            type: 'info',
            message: '已取消删除'
          })
        }
      })
    }
  
    /* 
    添加或更新功能权限
    */
    const addOrUpdatePermission = () => {
      permissionRef.value?.validate(async valid => {
        if (valid) {
          const { type } = permission          
          await saveOrUpdatePermissionApi(permission)
          ElMessage.success(`${type ==1 ? '修改' : '添加'}成功!`)
          resetData()
          fetchPermissionList()
        }
      })
    }
  
    /* 
    禁用
    */
    const disable = (row:any)=>{
      const is_disable = row.is_disable ===0?1:0
      reqGetDisabled(row.admin_menu_id,is_disable).then((res)=>{
      ElMessage.success('修改成功!')
      fetchPermissionList()
    })
    }
    /* 
    重置数据
    */
    const resetData = () => {
      dialogVisible.value = false
      Object.assign(permission, {
          type: 0,
          menu_name: '',
          menu_url: '',
          admin_menu_id:'',
          menu_sort:'',
      })
    }
  
  </script>
  